﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.IO;
using System.Text;
using System.Configuration;
using ESN.Models;
using System.Web.Script.Serialization;
using System.Web.Security;
using ESN.Helpers;

namespace ESN.Controllers
{
    [Authorize]
    public class CollectionController : Controller
    {
        private ESNCoreDbContext core = new ESNCoreDbContext();
        [AllowAnonymous]
        public ActionResult Index()
        {
            ViewBag.PublicCollections = core.Folders.Where(f => f.isPublic).OrderByDescending(f => f.FId).Take(20);
            Guid id = new Guid();
            if (PermissionHelper.IsAuthenticated(ref id))
            {
                ViewBag.YourCollections = core.Folders.Where(f => f.UserId == id);
                ViewBag.PublicCollections = core.Folders.Where(f => f.isPublic && f.UserId != id).OrderByDescending(f => f.FId).Take(20);
            }
            return View();
        }
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(string name, bool ispublic)
        {
            WebRequest request = WebRequest.Create("https://apis.live.net/v5.0/" + ConfigurationManager.AppSettings["Collections"]);
            request.Method = "POST";
            string postData = "{name: \"" + name + "\"}";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.Headers.Add("Authorization", "Bearer " + core.AppToken.Find(1).access_token);
            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            // Get the response.
            try
            {
                using (WebResponse response = request.GetResponse())
                using (Stream responseStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    // Display the content.
                    var parser = new JavaScriptSerializer();
                    LiveFolderStruct responseObj = parser.Deserialize<LiveFolderStruct>(responseFromServer);
                    //Insert to database here!
                    LiveFolder f = new LiveFolder();
                    f.FName = name;
                    f.FKey = responseObj.id;
                    f.isPublic = ispublic;
                    f.UserId = (Guid)Membership.GetUser().ProviderUserKey;
                    core.Folders.Add(f);
                    core.SaveChanges();
                    return RedirectToAction("View", new {id = f.FId});
                }
            }
            catch (WebException e)
            {
                using (WebResponse response = e.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    using (Stream bin = response.GetResponseStream())
                    {
                        string text = new StreamReader(bin).ReadToEnd();
                        ViewBag.Detail = text;
                        return View("Error");
                    }
                }
            }
        }

        public ActionResult View(int id)
        {
            var folder = core.Folders.Include("Attachments").Where(f => f.FId == id).OrderByDescending(f => f.FId);
            if (folder == null)
            {
                ViewBag.Detail = ESN.Languages.LangString.Load("not_exist", "Error");
                return View("Error");
            }
            return View(folder.Single());
        }
        [Authorize]
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            int id = 0;
            if (Int32.TryParse(Request.Form["FId"], out id))
            {
                var folder = core.Folders.Find(id);
                if (folder.UserId == (Guid)Membership.GetUser().ProviderUserKey)
                {
                    bool isImage = false;
                    if (file.ContentType == "image/pjpeg" ||
                        file.ContentType == "image/jpeg" ||
                        file.ContentType == "image/png" ||
                        file.ContentType == "image/gif")
                        isImage = true;

                    var response = "";
                    var realFileName = Path.GetFileName(file.FileName);

                    var binary = new byte[file.ContentLength];
                    file.InputStream.Read(binary, 0, file.ContentLength);

                    try
                    {
                        response = RemoteHelper.Put("https://apis.live.net/v5.0/" + folder.FKey + "/files/File-" + Request.Form["FId"] + "-AT-" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + "-NAME-" + realFileName + "?access_token=" + core.AppToken.Find(1).access_token, binary);
                    }
                    catch
                    {
                        ViewBag.Detail = "Error when upload image, try agian later!";
                        return View("Error");
                    }
                    var parser = new JavaScriptSerializer();
                    LiveFile liveResponse = parser.Deserialize<LiveFile>(response);

                    Attachment att = new Attachment();
                    att.isImage = isImage;
                    att.AKey = liveResponse.id;
                    att.UserId = folder.UserId;
                    att.AName = realFileName;
                    att.FId = id;

                    if (string.IsNullOrEmpty(Request.Form["isPublic"]))
                        att.isPublic = false;
                    else
                        att.isPublic = true;

                    if (isImage)
                        att.ASource = RemoteHelper.GetRedirect(liveResponse.source);
                    else
                        att.ASource = liveResponse.source;

                    core.Attachments.Add(att);
                    core.SaveChanges();
                }
                else
                {
                    ViewBag.Detail = "Error when upload image, try agian later!";
                    return View("Error");
                }
            }
            return RedirectToAction("View", new { id = id });
        }
    }
}
